package cn.yuxiaoyuan.service.impl;

import cn.yuxiaoyuan.article.doamin.ArticleType;
import cn.yuxiaoyuan.common.constant.CacheConstant;
import cn.yuxiaoyuan.common.util.R;
import cn.yuxiaoyuan.mapper.MenuMapper;
import cn.yuxiaoyuan.mapper.PermissionMapper;
import cn.yuxiaoyuan.service.IMenuService;
import cn.yuxiaoyuan.service.IPermissionService;
import cn.yuxiaoyuan.service.base.impl.BaseServiceImpl;
import cn.yuxiaoyuan.system.domain.Menu;
import cn.yuxiaoyuan.system.domain.Permission;
import cn.yuxiaoyuan.system.query.MenuQuery;
import cn.yuxiaoyuan.system.query.PermissionQuery;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author solargen
 * @version 1.0
 * @date 2025/5/19 9:49
 */
@Service
public class MenuServiceImpl extends BaseServiceImpl<Menu> implements IMenuService {
    @Autowired
    private MenuMapper menuMapper;

    @Override
    public R pageList(MenuQuery menuQuery) {
        PageHelper.startPage(menuQuery.getPage(),menuQuery.getSize());
        return R.ok(new PageInfo<>(menuMapper.pageList(menuQuery)));
    }

    @Override
    public R getTree() {

        //查询全部数据
        List<Menu> menuList = menuMapper.findAll();

        Map<Long,Menu> map = new HashMap<>();
        for (Menu menu : menuList) {
            //主键当key  本身当值
            map.put(menu.getId(),menu);
        }

        List<Menu> result = new ArrayList<>();
        for (Menu menu : menuList) {
            //判断当前这条数据是不是parentId是null
            if(menu.getParentId() == null){
                result.add(menu);
            }else {
                // 进入这个里面的都是儿子  找你的爹
                Long parentId = menu.getParentId();
                Menu pMenu = map.get(parentId);//找到你爹了
                pMenu.getChildren().add(menu);//把自己放入到你爹里面
            }
        }
        return R.ok(result);
    }
}
